package com.example.springinit.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;

/**
 * mq初始化类
 */
@Configuration
public class RocketMQConfig {
    private static final Log logger = LogFactory.getLog(RocketMQConfig.class);

    private static DefaultMQProducer SENDER;
    @Value("${rocketmq.producer.namesrvAddr}")
    private static String NAME_SERVER;
    @Value("${rocketmq.producer.sendMsgTimeout}")
    private static int sendMsgTimeout;

    private final static String PRODUCER_GROUP_NAME = "faceShowMQ";
    private final static String CONSUMER_GROUP_NAME = "faceShowMQ";

    public static DefaultMQProducer productInstance() {
        if (SENDER != null) {
            return SENDER;
        }
        synchronized (RocketMQConfig.class) {
            if (SENDER != null) {
                return SENDER;
            }

            SENDER = new DefaultMQProducer(PRODUCER_GROUP_NAME);
            SENDER.setNamesrvAddr(NAME_SERVER);
            SENDER.setInstanceName(UUID.randomUUID().toString());
            try {
                SENDER.start();
            } catch (MQClientException e) {
                logger.error("", e);
            }

            SENDER.setSendMsgTimeout(sendMsgTimeout);
            return SENDER;
        }

    }

    public static DefaultMQPushConsumer initConsumer() {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(CONSUMER_GROUP_NAME);
        consumer.setNamesrvAddr(NAME_SERVER);
        consumer.setConsumeMessageBatchMaxSize(10);
        logger.info("mq消费者 name_server:" + NAME_SERVER + "  生成consumerGroup:" + CONSUMER_GROUP_NAME);
        return consumer;
    }


    public void shutdown() {
        SENDER.shutdown();
    }


}
